package org.petstore.web.servlet;

import org.petstore.domain.Account;
import org.petstore.domain.CartItem;
import org.petstore.domain.Order;
import org.petstore.service.CartService;
import org.petstore.service.LogService;
import org.petstore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NewOrderServlet extends HttpServlet {
    private static final String VIEWORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    private Order order;
    private OrderService orderService;
    private List<CartItem> cart;
    private Account account;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        order = (Order) session.getAttribute("order");
        cart = (List<CartItem>) session.getAttribute("cart");
        account = (Account) session.getAttribute("account");
        orderService = new OrderService();
        CartService cartService = new CartService();
        if (order != null) {
            orderService.insertOrder(order);
            session.setAttribute("order", order);
            String username = account.getUsername();
            for (int i = 0; i < cart.size(); i++){
                cartService.updateItemByItemIdAndPay(username, cart.get(i).getItem().getItemId(),true);
            }
            //清空购物车
            session.removeAttribute("cart");
            cart = null;
            session.setAttribute("cart", cart);
            session.setAttribute("message", "Thank you, your order has been submitted.");
            if(account != null){
                HttpServletRequest httpRequest= request;
                String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());
                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + strBackUrl + " 生成订单 " + order;
                logService.insertLogInfo(account.getUsername(), logInfo);
            }
            request.getRequestDispatcher(VIEWORDER).forward(request, response);
        }
        else
        {
            session.setAttribute("message", "An error occurred processing your order (order was null).");
            request.getRequestDispatcher(ERROR).forward(request, response);
        }
    }
}
